package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.result.Result;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;


    /**
     * 营业额统计功能
     * @param begin
     * @param end
     * @return
     */
    @Override
    public Result turnoverStatistics(LocalDate begin, LocalDate end) {
        //新建一个集合对象用来存储开始的时间和最后的时间
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        //当结束时间等于开始则代表是最后一天
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //新建一个集合用来存储每天的营业额
        List<Double> turnoverList = new ArrayList<>();
        //遍历每天的时间，根据每天的时间来过去当天的营业额
        for (LocalDate date : dateList) {
            //获取当天的开始时间和结束时间
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //新建一个map存储条件用来查询数据库中的信息
            Map map = new HashMap<>();
            map.put("status", Orders.COMPLETED);
            map.put("begin", beginTime);
            map.put("end", endTime);
            Double turnover = orderMapper.sumByMap(map);
            turnover = turnover == null ? 0 : turnover;
            turnoverList.add(turnover);
        }
        //返回结果
        TurnoverReportVO vo = TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
        log.info("开始返回数据 vo : {}", vo);

        return Result.success(vo);
    }

    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public Result userStatistics(LocalDate begin, LocalDate end) {
        //新建一个集合对象用来存储开始的时间和最后的时间
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        //当结束时间等于开始则代表是最后一天
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //新建一个集合用来存储总用户量和每天新增的用户
        List<Integer> newUserCountList = new ArrayList<>();
        List<Integer> totalUserCountList = new ArrayList<>();
        //遍历每天的时间，根据每天的时间来过去当天的营业额
        for (LocalDate date : dateList) {
            //获取当天的开始时间和结束时间
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //新建一个map存储条件用来查询数据库中的信息
            Map map = new HashMap<>();
            //开始查询用户，先查询已注册的用户，再查询每日新增的用户
            map.put("end", endTime);
            Integer totalUserCount = userMapper.getUserCount(map);
            map.put("begin", beginTime);
            Integer newUserCount = userMapper.getUserCount(map);
            //将用户添加进集合
            totalUserCountList.add(totalUserCount);
            newUserCountList.add(newUserCount);
        }
        UserReportVO vo = UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .newUserList(StringUtils.join(newUserCountList, ","))
                .totalUserList(StringUtils.join(totalUserCountList, ","))
                .build();

        return Result.success(vo);
    }


    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public Result ordersStatistics(LocalDate begin, LocalDate end) {
        //新建一个集合对象用来存储开始的时间和最后的时间
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        //当结束时间等于开始则代表是最后一天
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //创建两个集合用来存储总订单和已完成的订单
        List<Integer> totalOrdersCountList = new ArrayList<>();
        List<Integer> validOrdersCountList = new ArrayList<>();
        //遍历集合，获取每天的时间
        for (LocalDate date : dateList) {
            //获取每日开始时间和结束时间
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //调用mapper获取到每日的总订单数和完成订单数
            Map map = new HashMap<>();
            //每日总和订单数
            map.put("end", endTime);
            map.put("begin", beginTime);
            Integer totalOrdersCount = orderMapper.getOrderCount(map);
            //获取每日有效订单数
            map.put("status", Orders.COMPLETED);
            Integer validOrdersCount = orderMapper.getOrderCount(map);
            //将订单放进集合
            totalOrdersCountList.add(totalOrdersCount);
            validOrdersCountList.add(validOrdersCount);
        }
        //通过stream流获取到总订单数量
        Integer totalOrderCount = totalOrdersCountList.stream().reduce(Integer::sum).get();
        //通过stream流获取到有效总订单数量
        Integer validOrderCount = validOrdersCountList.stream().reduce(Integer::sum).get();
        //订单完成率
        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0) {
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }

        //返回数据
        OrderReportVO vo = OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(totalOrdersCountList, ","))
                .validOrderCountList(StringUtils.join(validOrdersCountList, ","))
                .orderCompletionRate(orderCompletionRate)
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .build();

        return Result.success(vo);
    }

    /**
     * top10 统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public Result top10(LocalDate begin, LocalDate end) {
        //获取开始时间和最后的时间
        LocalDateTime beginTime = LocalDateTime.of(begin,LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end,LocalTime.MAX);
        //调用mapper方法来获取每个商品的售卖信息
        List<GoodsSalesDTO> goodsSalesDTOList = orderMapper.getTop10(beginTime,endTime);
        //用stream获取名字和销售数量
        List<String> nameList = goodsSalesDTOList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numberList = goodsSalesDTOList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        //返回结果
        SalesTop10ReportVO vo = SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(numberList,","))
                .build();

        return Result.success(vo);
    }

    /**
     * 导出excel表格
     * @param response
     */
    @Override
    public void export(HttpServletResponse response) {
        try {
            //获取上个月到现在的开始时间和最后时间
            LocalDate begin = LocalDate.now().minusDays(30);
            LocalDate end = LocalDate.now().minusDays(1);
            //获取相对路径
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("xlsx/运营数据报表模板.xlsx");
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);
            XSSFSheet sheet = excel.getSheet("Sheet1");
            //调用接口获取到
            BusinessDataVO vo = workspaceService.getBusinessData(LocalDateTime.of(begin,LocalTime.MIN),LocalDateTime.of(end,LocalTime.MAX));

            sheet.getRow(1).getCell(1).setCellValue("时间" + begin + "至" + end);
            //设置概览数据
            XSSFRow row = sheet.getRow(3);
            //设置营业额
            row.getCell(2).setCellValue(vo.getTurnover());
            //订单完成率
            row.getCell(4).setCellValue(vo.getOrderCompletionRate());
            //新增用户
            row.getCell(6).setCellValue(vo.getNewUsers());
            //下一行
            row = sheet.getRow(4);
            //有效订单
            row.getCell(2).setCellValue(vo.getValidOrderCount());
            //平均客价格
            row.getCell(4).setCellValue(vo.getUnitPrice());
            //遍历30次，在日期中加上每日详细数据
            for (int i = 0; i < 30; i++) {
                LocalDate time = begin.plusDays(i);
                vo = workspaceService.getBusinessData(LocalDateTime.of(time,LocalTime.MIN),LocalDateTime.of(time,LocalTime.MAX));
                //每次循环都自动下一行
                row = sheet.getRow(7 + i);
                //日期
                row.getCell(1).setCellValue(time.toString());
                //营业额
                row.getCell(2).setCellValue(vo.getTurnover());
                //有效订单
                row.getCell(3).setCellValue(vo.getValidOrderCount());
                //订单完成率
                row.getCell(4).setCellValue(vo.getOrderCompletionRate());
                //平均客人价格
                row.getCell(5).setCellValue(vo.getUnitPrice());
                //新增用户数量
                row.getCell(6).setCellValue(vo.getNewUsers());
            }

            excel.write(response.getOutputStream());

            excel.close();
            inputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
